package com.fingard.dsp.bank.directbank.hbc02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.io.File;
import java.util.*;

/**
 * @version 1.0
 */
public class HBC02Base extends DirectBase {
    //tag of MT940&MT942
    protected String tag61 = ":61:";
    protected String tag86 = ":86:";

    protected String splitFlag = "-\n";//内容分隔符

    protected String getCharset() {
        return getBankConfig().getCharset("utf-8");
    }

    /**
     * 文件移到
     *
     * @param source 原地址
     * @param target 新地址
     * @return
     */
    protected boolean renameTo(String source, String target) {
        boolean flag = new File(source).renameTo(new File(target));
        if (flag) {
            WriteBankLogLn2("文件：" + source + " ---移动至---\r\n" + target + "  成功");
        } else {
            WriteBankLogLn2("文件：" + source + " ---移动至---\r\n" + target + "  失败");
        }
        return flag;
    }

    protected String amtCheck(String amt) throws Exception {
        if (amt.startsWith(".")) {
            amt = "0" + amt;
        }
        if (amt.endsWith(".")) {
            amt = amt + "00";
        }
        amt=keepTwoDecimals(amt);
        return amt;
    }

    /**
     * 去掉小数点后两位的任何元素
     * @param amt
     * @return
     */
    public String keepTwoDecimals(String amt){
        if(amt.indexOf(".")+3<amt.length()){
            amt=amt.substring(0,amt.indexOf(".")+3);
        }
        return amt;
    }

    protected static boolean isLetter(char c){
        if(((c>='a'&&c<='z')   ||   (c>='A'&&c<='Z'))){
            return true;
        }
        return false;
    }

    /**
     * 获取ack状态并写入文件
     * @param ackFilePath
     * @param payDate
     * @param rspStatus
     * @return
     * @throws Exception
     */
    protected void getAckStatus(String ackFilePath,String payDate,String[] rspStatus,String level) throws Exception{
        String ackFile=ackFilePath+File.separator+payDate+File.separator
                + "ACK"+File.separator +rspStatus[0]+File.separator+rspStatus[0]+"_"+level+".txt";
        String contents=rspStatus[0]+"|"+rspStatus[1]+"|"+rspStatus[2]+"|";
        //写入文件
        FileHelper.appendFile(ackFile, contents, getCharset());
    }

    /**
     * 35长度校验
     * @param name
     * @return
     */
    protected String get35LenthName(String name) throws Exception{
        String charset="utf-8";
        String result="";
        byte[] payNames=new byte[35];
        if(name.getBytes(charset).length>35){
            System.arraycopy(name.getBytes(charset), 0, payNames, 0, 35);
            result=new String(payNames,charset);
            if(result.substring(result.length()-1).getBytes(charset)[0]<0){
                result=result.substring(0,result.length()-1);
            }
        }else {
            result=name;
        }
        return result;
    }

    /**
     * 拼接付款报文  人民币
     *
     * @return
     */
    protected StringBuilder PaymentXMLToFile(ReqSingle p_req1908) throws Exception{
        //****************第一行****************
        StringBuilder sb = new StringBuilder();
        sb.append("IFH,");//Record Type	M	AN	16	"IFH"
        sb.append("IFILE,");//File Format	M	AN	16	"IFILE"
        sb.append("CSV,");//File Type	M	AN	16	"CSV"
        sb.append(getBankConfig().getValueAsString("customerID")+",");//HSBC Connect Customer ID	C	AN	11	"企业在恒生银行申请文件上传功能时，由恒生银行提供；达芙妮ID：ABC57512001"
        sb.append(getBankConfig().getValueAsString("netID")+",");//HSBCnet Customer ID	C	AN	18	"企业在恒生银行申请文件上传功能时，由恒生银行提供；达芙妮ID：CHNASEGHC510056708"
        String date=Format.DateTime14Format.format(new Date());
        sb.append("PP_"+getBankConfig().getValueAsString("customerID")+"_"+date+",");//File Reference	M	AN	35	"Unique for each file (retention for 3 months)，格式：PP_（HSBC Connect Customer ID）_CCYYMMDDHHMMSS"
        sb.append(Format.Date10Format2.format(new Date())+",");//File Creation Date	M	N	10	CCYY/MM/DD
        sb.append(Format.Time8Format.format(new Date())+",");//File Creation Time	M	N	8	HH:MM:SS
        /*Authorization Type	M	AN	1
        “F” – File Level Authorised (Summary)（HSBCNet中文件上传类型，只可以看到上传文件的总笔数和总金额，无详细信息；只能2重授权，整批授权）
		“V” – File Level Authorised (Detail)（HSBCNet中文件上传类型，只可以看到上传文件详细信息；只能2重授权，整批授权）
		“P” – Instruction Level Authorised（HSBCNet中文件上传类型，只可以看到上传文件详细信息；只能3重授权，单笔授权）
        “A” – Pre Authorised（Host to Host）*/
        sb.append("A,");
        sb.append("1.0,");//File Version	M	N	3	"1.0"
        sb.append("3,");//Record Count	M	N	7	文件中所有数据笔数；File Header + Batch Header + Detail Record + Email Advice Record
        sb.append("U801\r\n");//Local Language Character Set	O	AN	4	U801
        //****************第二行****************
        sb.append("BATHDR,");//Record Type	M	AN	16	"BATHDR"
        sb.append("LTR,");//Instruction Type	M	AN	16	LTR
        sb.append("1,");//Total number of instructions in batch	M　	N	7	1
        sb.append(",");//Batch Reference	N	AN	35	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N		35	Blank
        sb.append("@1ST@,");//Constant Eye Catcher	M	AN	5	"@1ST@"
        String payDate=p_req1908.singleDetail.bookDate;
        if(StringHelper.isNullOrEmpty(payDate)){
            payDate=p_req1908.singleDetail.payDate;
        }
        sb.append(DateHelper.convertD10toD8(payDate)+",");//Value Date (YYYYMMDD)	M	N	8	当前日期
        sb.append(p_req1908.singleDetail.payAct+",");//First Party Account	M	N	35	企业付款的恒生银行账户
        sb.append("CNY,");//Transaction Currency*	M	AN	3	CNY
        sb.append(p_req1908.singleDetail.payAmount+",");//Transaction Amount*	C	N	14	(e.g. MAX with decimal place: 123456789012.00 or MAX without decimal place: 12345678901234)
        sb.append(",");//Template Mode	N　	AN	1	Blank
        sb.append(",");//Batch Template ID	N　	AN	16	Blank
        sb.append(",");//First Party Account Country	C　	AN	2	Blank
        sb.append(",");//First Party Account Institution	C　	AN	4	Blank
        sb.append("CNY,");//First Party Account Currency*	O　	AN	3	CNY
        sb.append(",");//Payment Amount in Debit account currency*	C　	N	20	Blank
        sb.append(get35LenthName(p_req1908.singleDetail.payName)+",");//First Party Name	M	AN	35	 企业在恒生银行付款账户名称，Max 35 位英文字符和最多11位中文字符
        sb.append(",");//First Party Information Line 1	C　	AN	35	Blank
        sb.append(",");//First Party Information Line 2	C　	AN	35	Blank
        sb.append(",");//First Party Information Line 3	C	AN	35	Blank
        sb.append(",");//First Party Information Line 4	C　	AN	35	Blank
        sb.append(",");//Payment Code	C　	AN	30	Blank
        sb.append(p_req1908.singleDetail.askNumber+",");//Reference Line 1	M 　	AN	16	Customer Reference NO
        sb.append(",\r\n");//Reference Line 2	CS　	AN	35	Blank
        //****************第三行****************
        sb.append("SECPTY,");//Record Type	M	AN	16	"SECPTY"
        sb.append(p_req1908.singleDetail.recAct+",");//Second Party Account Number	M	AN	32	收款人账号
        String recName=p_req1908.singleDetail.recName;
        String recName1=get35LenthName(recName);
        String recName2=get35LenthName(recName.replaceAll(recName1,""));
        String recName3=get35LenthName(recName.replaceAll(recName1+recName2,""));
        sb.append(recName1+",");//Second Party Name	O	AN	35	收款人名称1：收款人名称1+收款人名称2+收款人名称3，最大30位中文字符和35位英文字符；该字段中文字符最大11位
        sb.append(",");//Second Party Identifier	S　	AN	38	Blank
        sb.append(",");//Beneficiary Bank Number / ID	S　	N	9	Blank
        sb.append(",");//Beneficiary Branch Number	S　	N	4	Blank
        sb.append(",");//Transaction Code	S　	AN	6	Blank
        sb.append(p_req1908.singleDetail.payAmount+",");//Second Party Transaction Amount	S	N	14	(e.g. MAX with decimal place: 123456789012.00 or MAX without decimal place: 12345678901234)
        sb.append(",");//Entry Value Date (YYYYMMDD)	S　	N	8	Blank
        sb.append(",");//Second Party Reference	S　	AN	60	Blank
        sb.append(recName2+",");//Information Line 1	S　	AN	35	收款人名称2；收款人名称1+收款人名称2+收款人名称3，最大30位中文字符和35位英文字符；该字段中文字符最大11位
        sb.append(recName3+",");//Information Line 2	S　	AN	35	收款人名称3；收款人名称1+收款人名称2+收款人名称3，最大30位中文字符和35位英文字符；该字段中文字符最大8位
        sb.append(",");
        sb.append(",");//Information Line 3	S　	AN	35	Blank
        sb.append("N,");//Information Line 4	S　	AN	35	"N"
        sb.append("N,");//Advice Indicator	M	AN	1	Input “Y” if advice record needed
        sb.append(",");//WHT Indicator	M	AN	1	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N　		35	Blank
        sb.append(",");//Filler	N　		35	Blank
        //sb.append(",");//Filler	N　		35	Blank
        sb.append("@HVP@,");//Constant Eye Catcher	M	AN	5	"@HVP@"
        sb.append(",");//First Party Reference	N　	AN	35	Blank
        sb.append(",");//Payment Currency	N　	AN	3	Blank
        sb.append(",");//Template ID	N　	AN	16	Blank
        sb.append(",");//Exchange Rate	O　	N	12	Blank
        sb.append(",");//Intermediary Institution Bank ID/SWIFT Address Code	O　	AN	3	Blank
        sb.append(",");//Intermediary Institution Bank Name	C　	AN	35	Blank
        sb.append(",");//Intermediary Institution Bank Address Line 1	C　	AN	35	Blank
        sb.append(",");//Intermediary Institution Bank Address Line 2	C　	AN	35	Blank
        sb.append(",");//Intermediary Institution Bank Address Line 3	C　	AN	35	Blank
        sb.append(",");//Intermediary Institution Bank Address Line 4	C　	AN	35	Blank
        sb.append(",");//Intermediary Institution Bank ID/SWIFT Address	C　	AN	35	Blank
        sb.append(",");//Intermediary Institution Account Number	C　	N	34	Blank
        sb.append(",");//Beneficiary Bank ID/SWIFT Address Code	C　	AN	3	Blank
        sb.append(",");//36
        String recBankName=p_req1908.singleDetail.cnapsName;
        String recBankName1=get35LenthName(recBankName);
        String recBankName2=get35LenthName(recBankName.replaceAll(recBankName1,""));
        //收款行名称1：收款人名称1+收款人名称2=最大22位中文字符和35位英文字符；
        //同时36，37字段分别填写收款行名称；该字段中文字符最大11位
        sb.append(recBankName1+",");//37 Beneficiary Bank ID/SWIFT Address	C　	AN	34	"收款行行号或收款行名称1
        sb.append(recBankName2+",");//38 Beneficiary Bank Name 收款行名称2：收款人名称1+收款人名称2=最大22位中文字符和35位英文字符；
        sb.append(",");//Beneficiary Bank Address Line 1   C　	AN	35
        sb.append(",");//Beneficiary Bank Address Line 2	C　	AN	35	Blank
        sb.append(",");//Beneficiary Bank Address Line 3	C　	AN	35	Blank
        //sb.append(",");//Beneficiary Bank Address Line 4	N　	AN	35	Blank
        sb.append("CN,");//Beneficiary Bank Country	M　	AN	2	CN
        sb.append(",");//Beneficiary CHIPS UID	O　	AN	6	Blank
        String purpose=p_req1908.singleDetail.purpose;
        String purpose1=get35LenthName(purpose);
        String purpose2=get35LenthName(purpose.replaceAll(purpose1,""));
        String purpose3=get35LenthName(purpose.replaceAll(purpose1+purpose2,""));
        String purpose4=get35LenthName(purpose.replaceAll(purpose1+purpose2+purpose3,""));
        sb.append(purpose1+",");//Payment Details Line 1	O　	AN	35	"交易附言： 30位中英文字符，每个字段最大11位中文字符"
        sb.append(purpose2+",");//Payment Details Line 2	O　	AN	35
        sb.append(purpose3+",");//Payment Details Line 3	O　	AN	35
        sb.append(purpose4+",");//Payment Details Line 4	O　	AN	35
        sb.append("OUR,");//Details of Charges	M　	AN	3	"OUR"：手续费在付款人账户中扣取；
        sb.append(",");//Sender Charges	N　	AN	15	Blank
        sb.append(",");//Charges Account	N　	AN	34	Blank
        sb.append(",");//Instruction Code Line 1	O　	AN	35	Blank
        sb.append(",");//Instruction Code Line 2	O　	AN	35	Blank
        sb.append(",");//Instruction Code Line 3	O　	AN	35	Blank
        sb.append(",");//Instruction Code Line 4	O　	AN	35	Blank
        sb.append(",");//Bank to Bank Information Line 1	O　	AN	35	Blank
        sb.append(",");//Bank to Bank Information Line 2	O　	AN	35	Blank
        sb.append(",");//Bank to Bank Information Line 3	O　	AN	35	Blank
        sb.append(",");//Bank to Bank Information Line 4	O　	AN	35	Blank
        sb.append(",");//Bank to Bank Information Line 5	O　	AN	35	Blank
        sb.append(",");//Bank to Bank Information Line 6	O　	AN	35	Blank
        sb.append(",");//1st Exchange Contract Number	O　	AN	12	Blank
        sb.append(",");//1st Exchange Contract Amount	O　	N	15	Blank
        sb.append(",");//2nd Exchange Contract Number	O　	AN	12	Blank
        sb.append(",");//2nd Exchange Contract Amount 	O　	N	15	Blank
        sb.append("/CNAPS,");//Regulatory Reporting Line 1	M	AN	35	/CNAPS
        sb.append(",");//Regulatory Reporting Line 2	O　	AN	35	Blank
        sb.append(",");//Regulatory Reporting Line 3	O　	AN	35	Blank
        sb.append(",");//Advise By	O　	AN	1	Blank
        sb.append(",");//Advise By Number	O　	AN	20	Blank
        sb.append("\r\n");//Intermediary Bank Country	O　	AN	2	Blank
        return sb;
    }
}
